import allure
import pytest

from base.base_page import create_driver

# 用例失败后自动截图
@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call):
    """
    获取用例执行结果的钩子函数
    :param item:
    :param call:
    :return:
    """
    # 用例执行分为三个阶段：前置处理、用例执行、后置处理
    # 前置执行完会进入钩子方法，钩子方法获取rep，rep等于setup判断不是用例不会对前置截图
    # 执行用例会进入钩子方法，用例执行失败会进行结果截图
    # 后置跟前置一样
    # 获取钩子方法的调用结果
    outcome = yield
    rep = outcome.get_result()
    # 仅仅获取用例call执行结果是失败的情况，不包含setup/teardown
    # let's also access a fixture for the fun of it
    if rep.when == "call" and rep.failed: #and rep.failed删掉不管是否失败都截图，把call去掉setup和teardown都会截图
        # mode = "a" if os.pathsep.exists("failures") else "w"
        # with open("failures", mode) as f:
        #     # 记录失败用例
        #     if "tmpdir" in item .fixturenames:
        #         extra = "(%s)" % item.funcargs["tmpdir"]
        #     else:
        #         extra = ""
        #     f.write(rep.nodeid + extra + "\n")
        # 添加allure报告数量
        if hasattr(driver, "get_screenshot_as_png"):
            with allure.step('添加失败截图...'):
                allure.attach(driver.get_screenshot_as_png(), "失败截图", allure.attachment_type.PNG)

@pytest.fixture(scope="session")
def get_driver():
    global driver
    driver = create_driver()
    yield driver
    driver.quit()
